package com.cqq.auth.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import com.cqq.auth.service.bean.UserBean;
import com.cqq.common.core.constant.SessionConstant;

/**
 * <h3>Shiro权限工具类</h3>
 * 
 * @author xijq
 * @version 1.0.0
 * 
 */
public class AuthUtil {
	
	private AuthUtil(){}
	
	public static void login(String username,String password){
        Subject currentUser = SecurityUtils.getSubject();
        if(currentUser.isAuthenticated() && currentUser.getPrincipal().equals(username)){
        	;
        }
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);  
        currentUser.login(token);
	}
	
	public static void login(String username){
        Subject currentUser = SecurityUtils.getSubject();
        if(currentUser.isAuthenticated() && currentUser.getPrincipal().equals(username)){
        	;
        }
        UsernamePasswordToken token = new UsernamePasswordToken(username,new char[]{});  
        currentUser.login(token);
	}
	
	public static void logout(){
		Subject currentUser = SecurityUtils.getSubject();
		if(currentUser != null){
			currentUser.logout();
		}
	}
	
	public static UserBean getLoginUser(){
		Subject currentUser = SecurityUtils.getSubject();
		UserBean user=null;
		if(currentUser != null){
			Session session = currentUser.getSession(false);
			if (session!=null) {
				user=(UserBean)session.getAttribute(SessionConstant.LOGIN_USER);
			}
		}
		return user;
	}
	
	/**
	 * 验证用户是否具备某权限
	 * 
	 * @param permission 权限代码
	 *
	 * @return 用户是否具备某权限
	 */
	public static boolean hasPermission(String permission) {
		Subject subject = SecurityUtils.getSubject();
		return subject != null && subject.isPermitted(permission);
	}
	
}
